<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;


use think\Db;

/**
 * Game模型
 */
class BetsLog extends ModelBase
{

    protected $insert = ['create_time','trade_no'];

    /**
     * AI流水号自动完成
     */
    public function setTradeNoAttr()
    {

        return 'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);
    }

    /**
     * 连用户表
     */
    public function user(){
        return $this->belongsTo('Member','user_id','id');
    }

    /**
     * 连彩种表
     */
    public function lottery(){
        return $this->belongsTo('Lottery','lottery_id','id');
    }

    //关联transfer表
    public function getGameAttr(){
        return GamesLog::where(['order_no'=>$this->trade_no,'type'=>4])->find();
    }

    //关联transfer表
    public function kinguser(){
        return $this->belongsTo('GamblerKingInvestmentUser','user_investment_id','id');
    }
    /**
     * 连玩法表
     */
    public function play(){
        return $this->belongsTo('LotteryPlay','play_id','id');
    }

    /**
     * 连赌王表
     */

    public function king(){
        return $this->belongsTo('GamblerKing','king_id','id');
    }
    /**
     * 获取状态信息内容
     */
    public function getStateHtmlAttr(){

        switch ($this->state){
            case 1:
                $html='<span class="el-tag el-tag--mini">未开奖</span>';
                break;
            case 2:
                $html='<span class="el-tag el-tag--success">中奖</span>';
                break;
            case 3:
                $html='<span class="el-tag el-tag--danger">未中奖</span>';
                break;

            case 4:
                $html='<span class="el-tag el-tag--danger">已撤单</span>';
                break;

        }
        return $html;
    }
    /**
     * 开奖号码
     */
    public function getRewardNumberAttr()
    {

        $info=LotteryResult::get(['lottery_id'=>$this->lottery_id,'round'=>$this->round]);
        if($info){
           return $info['number'];
        }
        return '';
    }
    /**
     * 时间自动完成
     */
    public function setCreateTimeAttr()
    {

        return TIME_NOW;
    }

    /**
     * 时间自动完成
     */
    public function getCreateTimeAttr($value)
    {

        return date('Y-m-d H:i:s',$value);
    }



    /**
     * 开奖结算
     */
    public function  new_settlement($res,$member_list){
        $hit_number = $res['number'];
        $play=$this->play;
        $lottery=$this->lottery;
        $cate_symbol=$lottery->cate->symbol;
        $iszjokcount=0;
        if($this->is_old==1){
            include_once(ROOT_PATH.'extend/kaijiang/oldplay.php');
            $_zhushuyzclass = "Lib\\kaijiang\\oldplay";
            $_obj = new $_zhushuyzclass();
            $_fun=$play['symbol'];
            $arr=[
                'func'=>$_fun,
                'opencode'=>$hit_number,
                'tzcode'=>$this->number,
                'class2'=>$play->data['name']
            ];
            $iszjokcount=$_obj->check($arr);
        }else{
            include_once(ROOT_PATH.'extend/kaijiang/'.$cate_symbol.'.php');
            $_zhushuyzclass = "Lib\\kaijiang\\{$cate_symbol}";
            $_fun=$play['symbol'];
            $arr=[
                'playid'=>$_fun,
                'opencode'=>$hit_number,
                'tzcode'=>$this->number,
            ];
            $arrs[]=$arr;
            $_obj = new $_zhushuyzclass($arrs);
            $res=$_obj->check();

            $iszjokcount=$res[0]['zjcount'];
        }




       $reward_count=$iszjokcount['zjcount'];

        $zjcount=0;
        if($this->king_id>0){
            $king=GamblerKing::where(['id'=>$this->king_id])->lock(true)->find();
        }
        $game= GamesLog::where(['order_no'=>$this->trade_no])->find();
        Db::name('bet_result')->insert([
            'content'=>json_encode($iszjokcount),
            'bet_id'=>$this->id,
            'reward_count'=>$reward_count,
            'res_number'=>$hit_number,
            'create_time'=>TIME_NOW
        ]);
        if($reward_count>0){
            $is_winner=1;
            //中奖奖金

            $zjcount=$iszjokcount['zjcount'];
            $reward_money=self::$cate_symbol([
                'mode'=>$this->odds,
                'iszjcount'=>$reward_count,
                'beishu'=>$this->mult,
                'iszjokcount'=>$iszjokcount,
                'amount'=>$this->money,
                'itemcount'=>$this->injection_number,
                'zjcount'=>$zjcount,
                'yjf'=>$this->univalent
            ]);
            if($reward_money>$play['max_reward']){
                $reward_money=$play['max_reward']-$this->return_point_money;
                $reward_money_total=$play['max_reward'];
            }else{
                $reward_money_total=$reward_money+$this->return_point_money;
            }


            if($this->king_id>0){

                $invesment_reward_total=$reward_money_total;
                Db::name('investment_bet_log')->where(['trade_no'=>$this->trade_no])->update(['reward_money'=>$invesment_reward_total,'state'=>2,'profit'=>($invesment_reward_total-$this->money)/($this->entrust_count+1)]);

                //赌王可用余额增加
                $king->king_win_account+=$reward_money_total;
                $game_total_money=$reward_money_total;
                $invesment_user=GamblerKingInvestmentUser::get($this->user_investment_id);
                $invesment_user->stop_win_money_first+=($invesment_reward_total-$this->money);
                $invesment_user->king_win_account=$king->king_win_account;
                //写入流水
                KingBalanceLog::create([
                    'user_id'=>$king['user_id'],
                    'king_id'=>$this->king_id,
                    'number'=>$reward_money,
                    'is_add'=>1,
                    'remark'=>$lottery->data['name'].$this->round.'期中奖返还奖金'.$reward_money,
                    'type'=>2
                ]);
                if($this->return_point_money>0){
                    KingBalanceLog::create([
                        'user_id'=>$king['user_id'],
                        'king_id'=>$this->king_id,
                        'number'=>$this->return_point_money,
                        'is_add'=>1,
                        'remark'=>$lottery->data['name'].$this->round.'期中奖返点'.$this->return_point_money,
                        'type'=>2
                    ]);
                }

                $invesment_user->save();
                $king->save();


                if($this->pattern==2){
                    //对冲模式
                    $third_plan_programme=ThirdPlanProgramme::get($this->third_programme_id);
                    $third_plan_programme->profit+=($invesment_reward_total-$this->money);
                    $user_plan_programme=ThirdPlanUserProgramme::get(['user_investment_id'=>$this->user_investment_id]);
                    if($user_plan_programme['double_condition']==2){
                        $double_list=explode(',',$user_plan_programme['double_text']);
                        $third_plan_programme->throw=$double_list[0];
                        $third_plan_programme->double_key=0;

                    }
                    $third_plan_programme->save();
                }



            }else{
                //用户中奖
                $user_account=UserAccount::check(['user_id'=>$this->user_id,'wallet_id'=>1],false);
                $user_account->balance+=$reward_money_total;
                $user_account->save();
                //写入流水
                UserAccountLog::create([
                    'user_id'=>$this->user_id,
                    'wallet_id'=>1,
                    'before_blance'=>$user_account->balance-$reward_money_total,
                    'after_blance'=>$user_account->balance-$this->return_point_money,
                    'remark'=>$lottery->data['name'].$this->round.'期中奖返还奖金'.$reward_money,
                    'number'=>$reward_money,
                    'type'=>30,
                ]);
                if($this->return_point_money>0){

                    //写入流水
                    UserAccountLog::create([
                        'user_id'=>$this->user_id,
                        'wallet_id'=>1,
                        'before_blance'=>$user_account->balance-$this->return_point_money,
                        'after_blance'=>$user_account->balance,
                        'remark'=>$lottery->data['name'].$this->round.'期中奖返点'.$this->return_point_money,
                        'number'=>$this->return_point_money,
                        'type'=>30,
                    ]);
                    //写入游戏返点记录
                    GamesLog::create([
                        'user_id'=>$this->user_id,
                        'number'=>$this->return_point_money,
                        'type'=>6,
                        'remark'=>'自己下注中奖返点'.$this->return_point_money
                    ]);
                }
                $game_total_money=$reward_money;




            }


            $this->reward_money=$reward_money_total;
            $this->state=2;
            $this->reward_arr=implode(',',$iszjokcount['reward_arr']);
            $this->save();

            if( $game_total_money>$game->number){
                //赢
                GamesLog::where(['order_no'=>$this->trade_no,'type'=>4,'state'=>3])->update([
                    'state'=>4,
                    'profit'=>$game_total_money-$game->number,
                    'winner_money'=>$game_total_money-$game->number,
                ]);

            }elseif( $game_total_money<$game->number){
                //输
                GamesLog::where(['order_no'=>$this->trade_no,'type'=>4,'state'=>3])->update([
                    'state'=>4,
                    'profit'=>$game_total_money-$game->number,
                    'winner_money'=>$game_total_money-$game->number,
                    'is_winner'=>2,
                    'remark'=>$this->lottery->data['name'].':'.$this->play->data['name']

                ]);
            }else{
                //平
                GamesLog::where(['order_no'=>$this->trade_no,'type'=>4,'state'=>3])->update([
                    'state'=>4,
                    'is_winner'=>3
                ]);
            }

        }else{

            $is_winner=2;

            if($this->pattern==2){
                //对冲模式
                $user_plan_programme=ThirdPlanUserProgramme::get(['user_investment_id'=>$this->user_investment_id]);
                $third_plan_programme=ThirdPlanProgramme::get($this->third_programme_id);
                if($user_plan_programme['double_condition']==2){
                    $double_list=explode(',',$user_plan_programme['double_text']);
                   if(!empty($double_list[$third_plan_programme['double_key']+1])){
                       $third_plan_programme->throw=$double_list[$third_plan_programme['double_key']+1];
                       $third_plan_programme->double_key+=1;
                   }
                }
                $third_plan_programme->lost_count+=1;
                $third_plan_programme->profit-=$this->money;
                $third_plan_programme->save();
            }
            if($this->return_point_money>0) {

                $user_account=UserAccount::check(['user_id'=>$this->user_id,'wallet_id'=>1],false);
                $user_account->balance+=$this->return_point_money;
                $user_account->save();
                //写入流水
                UserAccountLog::create([
                    'user_id'=>$this->user_id,
                    'wallet_id'=>1,
                    'before_blance'=>$user_account->balance-$this->return_point_money,
                    'after_blance'=>$user_account->balance,
                    'remark'=>$play->data['name'].$this->round.'期未中奖返点'.$this->return_point_money,
                    'number'=>$this->return_point_money,
                    'type'=>30,
                ]);

                //写入游戏返点记录
                GamesLog::create([
                    'user_id'=>$this->user_id,
                    'number'=>$this->return_point_money,
                    'type'=>6,
                    'remark'=>'自己下注未中奖返点'.$this->return_point_money
                ]);


            }
            //未中奖
            $this->state=3;
            $this->save();
            GamesLog::where(['order_no'=>$this->trade_no,'type'=>4,'state'=>3])->update([
                'state'=>4,
                'profit'=>-$this->money,
                'is_winner'=>2,
                'remark'=>$this->lottery->data['name'].':'.$this->play->data['name']
            ]);
            $game_total_money=-$this->money;


        }
        if($this->entrust_count==0){
            //用户返点
            $this->agent_return($this->money,$this->user_id,$member_list,$member_list[$this->user_id]['username']);
            //增加个人下注业务流水
            $this->user->bets_total_balance+=$this->money;
            $this->user->bets_total+=$this->money;
            $this->user->save();
        }else{

            $invesment_user=GamblerKingInvestmentUser::get($this->user_investment_id);
            if($reward_count>0){
                Db::name('investment_bet_log')->where(['trade_no'=>$this->trade_no])->update(['reward_money'=>$reward_money/ ($this->entrust_count+1) ,'state'=>2,'profit'=>($reward_money-$this->money)/ ($this->entrust_count+1) ]);
            }else{
                Db::name('investment_bet_log')->where(['trade_no'=>$this->trade_no])->update(['reward_money'=>0,'state'=>3,'profit'=>-($this->money/ ($this->entrust_count+1) )]);
                $invesment_user->stop_win_money_first-=$this->money;
                $invesment_user->king_win_account=$king->king_win_account;
                $invesment_user->save();

            }




            //委托下注反点
            if($this->game->users){
                $uids=explode(',',trim( $this->game->users,","));
                if($uids){
                    foreach ($uids as $k=>$v){

                        $this->agent_return($this->money/($this->entrust_count+1),$v,$member_list,$member_list[$v]['username']);
                        //增加个人下注业务流水
                        Member::where(['id'=>$v])->setInc('bets_total_balance',$this->money/($this->entrust_count+1));
                        Member::where(['id'=>$v])->setInc('bets_total',$this->money/($this->entrust_count+1));
                    }
                }

            }
        }
        if($this->programme_id>0){
            //挂机处理
            $user_programme=PlanUserProgramme::get($this->programme_id);
            $plan_programme=$user_programme->programme;
            $throw=$user_programme->doubule;
            if($reward_count>0){
                //当前盈利
                $user_programme->current_win_money+=$game_total_money-$this->money;
                //当前亏损
                $user_programme->current_lose_money-=$game_total_money-$this->money;

                if($is_winner==1){
                    $is_reward=1;
                    $plan_programme->win_count+=1;

                }else{
                    $is_reward=0;
                }

            }else{

                //当前盈利
                $user_programme->current_win_money-=$this->money;
                //当前亏损
                $user_programme->current_lose_money+=$this->money;
                $is_reward=0;
            }
            $user_programme->current_times=$throw->get_game($user_programme->current_times,$is_reward);
            $plan_programme->win_rate=format_money($plan_programme->win_count/$plan_programme->bets_count*100,2);
            $plan_programme->save();
            if($user_programme->is_stop_win==1){
                if($user_programme->current_win_money>=$user_programme->stop_win_money){
                    $plan_programme->state=4;
                    $plan_programme->has_end_time=TIME_NOW;
                }
            }
            if($user_programme->is_stop_lose==1){
                if($user_programme->current_lose_money>=$user_programme->stop_lose_money){
                    $plan_programme->state=4;
                    $plan_programme->has_end_time=TIME_NOW;
                }
            }
            if($user_programme['current_round']==$user_programme['round']){
                $user_programme->state=4;
                $plan_programme->has_end_time=TIME_NOW;
            }
            $user_programme->save();

        }

        if($this->king_id>0){
            if($is_winner==1){
                //赢次数
                $king->king_win_count+=1;

            }else{
                //输次数

                $king->king_lose_count+=1;
            }
            //完成周期
            $order=GamesLog::where(['king_id'=>$this->king_id,'state'=>4,'type'=>4,'entrust_count'=>0,'id'=>['lt',$game['id']]])->order('id desc')->find();

            if($order){
                if($order['is_winner']!=$is_winner){
                    $king->king_success_cycle+=1;
                }
            }


            //正确率
            $error_rate=format_money($king->king_win_count/($king->king_win_count+$king->king_lose_count)*100,2);
            $king->king_accuracy_rate=$error_rate;

            //当前连中
            if($order){

                if($is_winner==1){
                    //这把赢
                    if($order['is_winner']==2){
                        //上把输
                        $king->king_continuous_error=0;
                        $king->king_current_win=1;
                    }else{
                        //上把赢
                        $king->king_current_win+=1;
                        if( $king->king_current_win>$king->king_max_win){
                            //最大连赢
                            $king->king_max_win=$king->king_current_win;
                        }
                    }
                }else{
                    //这把输
                    $king->king_current_win=0;
                    if($order['is_winner']==1){
                        //上把赢
                        $king->king_current_win=0;
                        $king->king_continuous_error=1;

                    }else{
                        //上把输
                        $king->king_continuous_error+=1;
                        if( $king->king_continuous_error>$king->king_max_continuous_error){
                            //最大连输
                            $king->king_max_continuous_error=$king->king_continuous_error;
                        }
                    }


                }
            }else{
                if($is_winner==1){
                    if( $king->king_current_win>0){
                        $king->king_current_win+=1;
                        if( $king->king_current_win>$king->king_max_win){
                            //最大连赢
                            $king->king_max_win=$king->king_current_win;
                        }

                    }else{
                        $king->king_current_win=1;
                    }
                    $king->king_continuous_error=0;
                }else{
                    if( $king->king_continuous_error>0){
                        //当前连输
                        $king->king_continuous_error+=1;
                        if( $king->king_continuous_error>$king->king_max_continuous_error){
                            //最大连输
                            $king->king_max_continuous_error=$king->king_continuous_error;
                        }

                    }else{
                        $king->king_continuous_error=1;
                    }
                    $king->king_current_win=0;
                }

            }

            $king->save();
        }


    }


    /***
     *代理递归返点
     *
     */

    public function agent_return($money,$uid,$member_list,$usrename,$point=0){
        if($uid>0){
            $leader_id=$member_list[$uid]->leader_id;
            if(!$point){
                $point=UserLevel::where(['id'=>$member_list[$uid]['level_id']])->value('game_return');
            }
            if($leader_id>0 &&  $member_list[$leader_id]['level_id']>$member_list[$uid]['level_id']){

                $leader_point=UserLevel::where(['id'=>$member_list[$leader_id]['level_id'] ])->value('game_return');
                if($leader_point>$point){
                    $point_money=format_money(($leader_point-$point)*0.05*$money/100,2);
                    if($point_money>=0.01){
                        $user_account=UserAccount::check(['user_id'=>$leader_id,'wallet_id'=>1],false);
                        $user_account->balance+=$point_money;
                        $user_account->save();
                        //写入流水
                        UserAccountLog::create([
                            'user_id'=>$leader_id,
                            'wallet_id'=>1,
                            'before_blance'=>$user_account->balance-$point_money,
                            'after_blance'=>$user_account->balance,
                            'remark'=>'下注返点'.$point_money,
                            'number'=>$point_money,
                            'type'=>30,
                        ]);
                        //写入游戏返点记录
                        GamesLog::create([
                            'user_id'=>$leader_id,
                            'number'=>$point_money,
                            'type'=>6,
                            'remark'=>$usrename.'下注产生返点'.$point_money
                        ]);
                    }
                }
                if($leader_point<$point){
                    $leader_point=$point;
                }
                $this->agent_return($money,$leader_id,$member_list,$usrename,$leader_point);
            }else{
                if($leader_id>0){
                    $this->agent_return($money,$leader_id,$member_list,$usrename,$point);
                }

            }
        }

    }


    protected function lhc($res){

        $okamount = 0;
        if(strstr($res["mode"],'|')){
            $mode = explode('|',$res["mode"]);
            for($i=0;$i<count($mode);$i++){
                if($res["iszjcount"][$i]>0){
                    $okamount +=($res['amount']/$res['itemcount'])*$mode[$i]*$res['beishu']*$res['iszjokcount'][$i];
                }
            }
        }else{
            $okamount = ($res['amount']/$res['itemcount'])*$res['mode']*$res['beishu']*$res['iszjokcount'];
        }

        return $okamount;
    }

    protected function ssc($res){
        $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        return $okamount;
    }
    protected function k3($res){
        $okamount = ($res['amount']/$res['itemcount'])*$res['mode']*$res['zjcount'];
        return $okamount;
    }
    protected function x5($res){
        $okamount = 0;
        if(strstr($res["mode"],'|')){
            $amount = explode('|',$res["mode"]);
            for($i=0;$i<count($amount);$i++){
                if($res['iszjokcount'][$i]!=0){
                    $okamount = $amount[$i]*$res['iszjokcount'][$i]*$res['beishu']*$res['yjf'];
                }
            }
        }else{

            $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        }
        return $okamount;
    }
    protected function kl10f($res){
        $okamount = 0;
        $rules = M('wanfa')->where(['typeid'=>$res['typeid'],'playid'=>$res['playid']])->find();
        if($rules){
            $defaultfandian = 0.13;
            $userinfo = [];
            $userinfo = M('member')->where(['id'=>$res['uid']])->find();
            $fandian = $userinfo['fandian'];
            if($rules['rate']>0){
                $amount = $res['mode']  *$res['yjf']*$res['beishu'];
                $okamount = $amount*$res['zjcount'];
            }else{
                $amount = (($rules['maxjj']/2) - ($defaultfandian-($fandian/100-$res['repoint']/100)) * $rules['totalzs'])*$res['yjf']*$res['beishu'];
                $okamount = $amount*$res['zjcount'];
            }
        }else{

        }
        return $okamount;
    }
    protected function pk10($res){
        $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        return $okamount;
    }
    protected function dpc($res){

        $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        return $okamount;
    }
    protected function keno($res){
        $okamount = 0;
        if(strstr($res["mode"],'|')){
            $amount = explode('|',$res["mode"]);
            for($i=0;$i<count($amount);$i++){
                if($res["iszjcount"][$i]>0){
                    $okamount = $okamount+($amount[$i]*$res["iszjcount"][$i])*$res['beishu']*$res['yjf'] ;
                    break;
                }
            }
        }else{
            $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        }
        return $okamount;

    }
}
